<template>
	<div class="table-box">
		<div style="width: 100%">
			<el-tabs v-model="tabStatus" class="demo-tabs" @tab-change="changeStatus">
				<el-tab-pane label="全部" name=""></el-tab-pane>
				<el-tab-pane label="待取号" :name="102"></el-tab-pane>
				<el-tab-pane label="已取号" :name="103"></el-tab-pane>
				<el-tab-pane label="已发货" :name="104"></el-tab-pane>
				<el-tab-pane label="已废弃" :name="201"></el-tab-pane>
			</el-tabs>
		</div>
		<ProTable
			ref="proTable"
			title="我的订单"
			:columns="columns"
			:requestApi="getTableList"
			:initParam="initParam"
			:dataCallback="dataCallback"
		>
			<!-- 表格 header 按钮 -->
			<template #tableHeader="scope">
				<!-- <el-button type="primary" :icon="CirclePlus" @click="openDrawer('新增')">新增地址</el-button> -->
				<el-button type="primary" :icon="Printer" plain @click="printAll(scope.selectedList)">批量打印面单</el-button>
				<el-button type="primary" :icon="Printer" plain @click="printLabelAll(scope.selectedList)">批量打印标签</el-button>
				<el-button type="primary" :icon="Download" plain @click="ExportXlsx">导出订单数据</el-button>
				<el-button
					v-upload-file="{
						type: ['xls', 'xlsx'],
						size: 5,
						limit: 1
					}"
					@upload="readExcelFile"
					type="primary"
					plain
					:icon="UploadFilled"
					>D82订单补全</el-button
				>
				<el-button @click="downLoadModel" type="primary" plain :icon="Download">D82补全模版下载</el-button>

				<!-- <el-button type="primary" plain @click="toDetail">To 子集详情页面</el-button> -->
				<el-button v-auth="'batchAdd'" type="danger" :icon="Delete" plain :disabled="!scope.isSelected"> 批量删除用户 </el-button>
				<el-select class="selectClass" v-model="printer" placeholder="选择打印机">
					<el-option v-for="item in printerList" :key="item.name" :label="item.name" :value="item.name" />
				</el-select>
			</template>
			<!-- 表格操作 -->
			<template #operation="scope">
				<!-- <el-button type="primary" link :icon="View" @click="openDrawer('查看', scope.row)">查看</el-button> -->
				<el-button
					v-if="scope.row.status == 102 || scope.row.status == 103"
					type="primary"
					link
					:icon="EditPen"
					@click="openDrawer('编辑', scope.row)"
					>编辑</el-button
				>
				<el-button type="primary" link :icon="View" @click="openDrawer('查看', scope.row)">查看</el-button>
				<el-button type="primary" link :icon="Printer" @click="print(scope.row)">面单</el-button>
				<el-button type="primary" link :icon="Printer" @click="printLable(scope.row)">标签</el-button>
				<el-button type="primary" link :icon="Memo" @click="openLog(scope.row)">日志</el-button>

				<el-button v-if="scope.row.status == 102 || scope.row.status == 103" link :icon="Delete" @click="deleteAccount(scope.row)"
					>废弃</el-button
				>
			</template>
		</ProTable>
		<UserDrawer ref="drawerRef" />
		<ImportExcel ref="dialogRef" />
		<el-drawer size="500" v-model="logDraw" title="订单日志">
			<div>
				<el-empty v-if="!logList.length" description="暂无订单日志" />

				<el-timeline>
					<el-timeline-item v-for="(activity, index) in logList" :key="index" :timestamp="activity.create_time">
						{{ activity.info }}
					</el-timeline-item>
				</el-timeline>
			</div>
		</el-drawer>

		<el-dialog v-model="dialogVisible" title="导入结果" width="600px" :before-close="handleClose">
			<div>
				<div style="margin-bottom: 20px">
					共<span style="font-size: 16px; color: #000000"> {{ total }}</span> 条,导入成功
					<span style="font-size: 16px; color: green">{{ total - errorList.length }}</span> 条,失败
					<span style="font-size: 16px; color: red">{{ errorList.length }} </span> 条
				</div>
				<el-table v-if="errorList.length" :data="errorList" style="width: 100%" height="500px">
					<el-table-column prop="line" label="行数" width="80" />
					<el-table-column prop="first_waybill_no" label="订单号" width="150" />
					<el-table-column prop="errMsg" label="错误原因" />
				</el-table>
			</div>
			<template #footer>
				<span class="dialog-footer">
					<el-button type="primary" @click="dialogVisible = false"> 确定 </el-button>
				</span>
			</template>
		</el-dialog>

		<el-dialog v-model="cheackRes" title="重复打印检测" width="500px" :before-close="handleClose">
			<div>
				<div style="margin-bottom: 20px">以下主运单号重复打印，请确认继续打印</div>
				<el-table v-if="errorData.length" :data="errorData" style="width: 100%" height="500px">
					<el-table-column prop="errMsg" label="运单号">
						<template #default="{ row }">
							<div>
								{{ row }}
							</div>
						</template>
					</el-table-column>
				</el-table>
			</div>
			<template #footer>
				<span class="dialog-footer">
					<el-button type="" @click="cheackRes = false"> 取消 </el-button>
					<el-button type="primary" @click="goOnPrint"> 继续打印 </el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="tsx" name="myList">
import { ref, reactive, onMounted, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
	orderList,
	orderCancel,
	orderUpdate,
	printExpressLabel,
	printOrderLabel,
	completionOrder,
	printTimes,
	listLog,
	checkExpress
} from "@/api/modules/order";
import { ColumnProps } from "@/components/ProTable/interface";
import { useHandleData } from "@/hooks/useHandleData";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import UserDrawer from "@/views/orderList/components/UserDrawer.vue";
import { Memo, Delete, EditPen, Printer, Download, UploadFilled, View } from "@element-plus/icons-vue";
import { listClientAddress, updateClientAddress, createClientAddress, delClientAddress } from "@/api/modules/address";
import { doConnect, doPrintHandover, doPrint } from "@/utils/print";
import { ElLoading } from "element-plus";
import XLSX from "xlsx-js-style";
import _ from "lodash";
import { AddressCorrectNew, downTemplate } from "@/api/base/index";
import { sheet2Data } from "@/utils/excel";
import { goodsList } from "@/api/modules/goods";
import { listChannel } from "@/api/modules/makeorder";
import { listPort } from "@/api/modules/wallet";
const logDraw = ref(false);
const logList: any = ref([]);
const dialogVisible = ref(false);
const handleClose = () => {
	dialogVisible.value = false;
	cheackRes.value = false;
};
const openLog = (row: any) => {
	logDraw.value = true;
	listLog({
		tid: row.tid
	}).then((res: any) => {
		logList.value = res.data.list;
	});
};

const downloadHandler = (data: any) => {
	// 匹配任意文件类型：type : "application/octet-stream"
	let blob = new Blob([data], {
		type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
	});
	// 获取heads中的filename文件名
	let downloadElement = document.createElement("a");
	// 创建下载的链接
	let href = window.URL.createObjectURL(blob);
	downloadElement.href = href;
	// 下载后文件名
	downloadElement.download = "D82订单补全.xlsx";
	document.body.appendChild(downloadElement);
	// 点击下载
	downloadElement.click();
	// 下载完成移除元素
	document.body.removeChild(downloadElement);
	// 释放掉blob对象
	window.URL.revokeObjectURL(href);
};
const downLoadModel = () => {
	downTemplate({}).then(res => {
		downloadHandler(res);
	});
};
const TableList: any = ref([]);
/**
 * 把文件按照二进制进行读取
 * @param file
 * @returns
 */
const readFile = (file: File) => {
	return new Promise(resolve => {
		let reader = new FileReader();
		reader.readAsArrayBuffer(file);
		reader.onload = ev => {
			resolve(ev.target?.result);
		};
	});
};

const addressCorrect = (address: any) => {
	return new Promise((resolve, reject) => {
		if (address) {
			AddressCorrectNew({
				country: "CN",
				address: address
			}).then((res: any) => {
				resolve({
					province: res.data.state,
					city: res.data.city,
					district: res.data.district,
					detailed: res.data.detail
				});
			});
		} else {
			resolve({
				province: "",
				city: "",
				district: "",
				detailed: ""
			});
		}
	});
};
/**
 * 根据sheet索引读取Excel文件中的数据
 /**@param file 文件
 /** @param sheetIndex excel文件中sheet表索引 默认是从0开始
 /**@returns  将表中的数据以json形式的数据返回
*/
const errorList = ref([]);
const total = ref(0);
const readExcelFile = async (e: any) => {
	let data = await readFile(e);
	let workbook = XLSX.read(data);
	let worksheet = workbook.Sheets[workbook.SheetNames[0]];
	// data = XLSX.utils.sheet_to_json(worksheet);
	let file = sheet2Data(worksheet, "AW");
	let arr = [
		"包裹号",
		"运单号",
		"包裹重量(KG)",
		"收件人姓名",
		"收件地址（需要填写正确省市区）",
		"收件人手机号码",
		"收件人邮编",
		"备注",
		"快递产品类型",
		"货物类型",
		"卫衣",
		"开衫",
		"毛衣/针织衫",
		"衬衫",
		"T恤",
		"背心",
		"内衣",
		"连衣裙",
		"半身裙",
		"休闲裤",
		"短款",
		"牛仔裤",
		"羊绒大衣",
		"风衣",
		"西服",
		"羽绒服",
		"棉服",
		"夹克",
		"发夹",
		"发圈",
		"发箍",
		"项链",
		"手链/脚链",
		"耳环",
		"运动鞋",
		"皮鞋",
		"拖鞋",
		"凉鞋",
		"长靴",
		"双肩包",
		"皮包",
		"布包",
		"帽子",
		"袜子",
		"手套",
		"腰带",
		"丝巾",
		"围巾",
		"文件"
	];
	// let arrKey = ["weight", "order_no", ""];
	console.log(file[4]);
	console.log(arr);

	if (!_.isEqual(arr, file[4])) {
		ElMessage.error("上传模版错误");
		return false;
	}
	let goodList = file.splice(5, file.length - 1);
	let arrList: any = [];
	for (let index in goodList) {
		const detail = [];
		const item = goodList[index];
		const address: any = await addressCorrect(item[4]);
		for (let i = 0; i < item.length; i++) {
			if (i >= 10 && item[i]) {
				detail.push({
					cate2: arr[i],
					num: item[i]
				});
			}
		}
		let obj: any = {
			order_no: item[0],
			first_waybill_no: item[1],
			weight_report: item[2],
			receiver_info: {
				name: item[3],
				area_code: 86,
				mobile: item[5],
				postcode: item[6],
				nation: "中国",
				province: address.province,
				city: address.city,
				district: address.district,
				detailed: address.detailed
			},
			remarks: item[7],
			goods_type: item[9],
			express_type: item[8],
			detail: detail,
			line: Number(index) + 5
		};
		arrList.push(obj);
	}
	total.value = arrList.length;
	let chunkList = _.chunk(arrList, 10);
	errorList.value = [];
	for (let index = 0; index < chunkList.length; index++) {
		const element = chunkList[index];
		await completionOrderChunk(element);
	}
	ElMessage.success("上传完成");
	dialogVisible.value = true;
	proTable.value.getTableList();
};
const completionOrderChunk = (list: any) => {
	return new Promise<void>((resolve, reject) => {
		completionOrder({
			list: list
		}).then((res: any) => {
			errorList.value = errorList.value.concat(res.data.errorList);
			resolve(res.msg);
		});
	});
};
const printerList = ref();
const printLoading = ref();
const back = ref();
const printer = ref("");
const printType = ref("");
watch(back, () => {
	printTimes({ document_id: back.value.printStatus[0].documentID, type: printType.value }).then(res => {});
	VPrintBack(back);
});
const VPrintBack = //打印返回
	(res: any) => {
		printLoading.value.close();
	};
const goodsCateList: any = ref([]);
onMounted(() => {
	let socket = doConnect();
	goodsList({
		cate: 0
	}).then((res: any) => {
		goodsCateList.value = res.data.list.map((i: any) => {
			return i.name;
		});
	});
	socket.onmessage = function (event: any) {
		console.log(JSON.parse(event.data));
		let res = JSON.parse(event.data);
		if (res.cmd === "getPrinters") {
			printerList.value = res.printers;
			console.log(printerList.value);
		}
		if (res.cmd === "print") {
			printLoading.value = ElLoading.service({
				lock: true,
				text: "打印中...",
				background: "rgba(0, 0, 0, 0.7)"
			});
		}
		if (res.cmd === "notifyPrintResult" && res.taskStatus === "printed") {
			back.value = res;
		}
		if (res.status == "failed") {
			printLoading.value.close();
			ElMessage.error(res.msg);
		}
	};
});

//单独打印标签
const printLable = (params?: any) => {
	printOrderLabel({
		id: [params.id]
	}).then((res: any) => {
		printType.value = "label";
		doPrint(res.data.list, res.data.templateURL, printer.value);
	});
};
const checkExpressOrders = (list: any) => {
	const waybill_nos = list.map((item: any) => {
		return item.first_waybill_no;
	});
	return new Promise((resolve, reject) => {
		checkExpress({
			waybill_nos: waybill_nos
		}).then((res: any) => {
			resolve(res.data.errorData);
		});
	});
};
const errorData: any = ref([]);
const cheackRes = ref(false);
const printList: any = ref([]);
//批量面单
const printAll = async (list: any) => {
	if (!list.length) {
		ElMessage.error("请选择订单");
		return;
	}
	errorData.value = await checkExpressOrders(list);
	if (errorData.value.length) {
		cheackRes.value = true;
		printList.value = list;
	} else {
		let arr = list.map((i: any) => {
			return i.first_waybill_no;
		});
		printExpressLabel({
			waybill_no: arr
		}).then((res: any) => {
			res.data.printData.forEach((item: any) => {
				printType.value = "";
				doPrintHandover([item], printer.value);
			});
		});
	}
};
//单独打印面单
const print = async (params?: any) => {
	errorData.value = await checkExpressOrders([params]);
	if (errorData.value.length) {
		cheackRes.value = true;
		printList.value = [params];
	} else {
		printExpressLabel({
			waybill_no: [params.first_waybill_no]
		}).then((res: any) => {
			printType.value = "";
			doPrintHandover(res.data.printData, printer.value);
		});
	}
};
const goOnPrint = () => {
	cheackRes.value = false;
	proTable.value.clearSelection();
	let arr = printList.value.map((i: any) => {
		return i.first_waybill_no;
	});
	printExpressLabel({
		waybill_no: arr
	}).then((res: any) => {
		res.data.printData.forEach((item: any) => {
			printType.value = "";
			doPrintHandover([item], printer.value);
		});
	});
};
//批量标签
const printLabelAll = (list: any) => {
	if (!list.length) {
		ElMessage.error("请选择订单");
		return;
	}
	let arr = list.map((i: any) => {
		return i.id;
	});
	printOrderLabel({
		id: arr
	}).then((res: any) => {
		res.data.list.forEach((item: any) => {
			printType.value = "label";
			doPrint([item], res.data.templateURL, printer.value);
		});
	});
};
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref();
const tabStatus = ref<any>("");
// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
	status: tabStatus.value
});
const changeStatus = (name: any) => {
	proTable.value.getTableList();
};
// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，那么你可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
	return {
		list: data.list,
		total: data.count
		// pageNum: data.pageNum,
		// pageSize: data.pageSize
	};
};
// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const param = ref({});
const getTableList = (params: any) => {
	params.status = tabStatus.value;
	param.value = params;
	let newParams = JSON.parse(JSON.stringify(params));
	return orderList(newParams);
};

// 页面按钮权限（按钮权限既可以使用 hooks，也可以直接使用 v-auth 指令，指令适合直接绑定在按钮上，hooks 适合根据按钮权限显示不同的内容）
const status = reactive([
	{
		userLabel: "是",
		userStatus: true
	},
	{
		userLabel: "否",
		userStatus: false
	}
]);
const getPostList = () => {
	return new Promise<void>((resolve, reject) => {
		listPort({
			status: 1,
			limit: 9999
		}).then((res: any) => {
			let data: any = {
				data: res.data.data
			};
			resolve(data);
		});
	});
};
const getChannelList = () => {
	return new Promise<void>((resolve, reject) => {
		listChannel({
			line_id: 0
		}).then((res: any) => {
			let data: any = {
				data: res.data.list
			};
			resolve(data);
		});
	});
};
// 表格配置项
const columns: ColumnProps[] = [
	{ type: "selection", fixed: "left", width: 80 },
	// { type: "index", label: "#", width: 80, fixed: "left" },
	// { type: "expand", label: "Expand", width: 100 },
	{
		prop: "first_waybill_no",
		label: "主运单号",
		search: { el: "input" },
		fixed: "left",
		width: 160
	},
	{
		prop: "second_waybill_no",
		label: "从运单号",
		search: { el: "input" },
		width: 160
	},
	{
		prop: "receiver.user_mark",
		label: "客户唛头",
		width: 120
	},
	{
		prop: "receiver_name",
		label: "收件人",
		width: 120,
		search: { el: "input" },
		render: (scope: { row: any }) => {
			return <>{scope.row.receiver ? scope.row.receiver.name : ""}</>;
		}
	},
	{
		prop: "address",
		label: "状态",
		width: 100,
		render: (scope: { row: any }) => {
			return (
				<>
					<el-tag
						style="margin-right:10px"
						type={
							scope.row.status == 102 ? "info" : scope.row.status == 103 ? "" : scope.row.status == 104 ? "success" : "danger"
						}
					>
						{scope.row.status == 102
							? "待取号"
							: scope.row.status == 103
							? "已取号"
							: scope.row.status == 104
							? "已发货"
							: "已废弃"}
					</el-tag>
				</>
			);
		}
	},
	{
		prop: "address",
		label: "订单标识",
		width: 200,
		render: (scope: { row: any }) => {
			return (
				<>
					<el-tag style="margin-right:10px" type={scope.row.label_data.is_error ? "success" : "info"}>
						{scope.row.label_data.is_error ? "异" : "异"}
					</el-tag>
					<el-tag style="margin-right:10px" type={scope.row.label_data.is_collect ? "success" : "info"}>
						{scope.row.label_data.is_collect ? "揽" : "揽"}
					</el-tag>
					<el-tag style="margin-right:10px" type={scope.row.label_data.is_complete ? "success" : "info"}>
						{scope.row.label_data.is_complete ? "完" : "完"}
					</el-tag>
					{scope.row.error ? (
						<el-tooltip class="box-item" effect="dark" content={scope.row.error} placement="top">
							<el-tag type={scope.row.label_data.is_pay ? "success" : "info"}>
								{scope.row.label_data.is_complete ? "支" : "支"}
							</el-tag>
						</el-tooltip>
					) : (
						<el-tag type={scope.row.label_data.is_pay ? "success" : "info"}>
							{scope.row.label_data.is_complete ? "支" : "支"}
						</el-tag>
					)}
				</>
			);
		}
	},
	{
		prop: "tid",
		label: "系统单号",
		search: { el: "input" },
		width: 180
	},

	{
		prop: "line.line_name",
		label: "线路",
		width: 120
	},
	{
		prop: "channel_id",
		label: "走件渠道",
		width: 160,
		enum: getChannelList,
		search: { el: "select", props: { filterable: true } },
		fieldNames: { label: "name", value: "id" },
		render: (scope: { row: any }) => {
			return <>{scope.row.channel ? scope.row.channel.name : ""}</>;
		}
	},

	{ prop: "client.username", label: "客户名称", width: 120 },

	{
		prop: "order_no",
		label: "来源单号",
		search: { el: "input" },
		width: 160
	},

	// 多级 prop
	{
		prop: "receiver",
		label: "电话",
		width: 150,
		render: (scope: { row: any }) => {
			return (
				<>
					+{scope.row.receiver.area_code} {scope.row.receiver.mobile}
				</>
			);
		}
	},
	{
		prop: "port",
		label: "走件口岸",
		width: 160,
		enum: getPostList,
		search: { el: "select", props: { filterable: true } },
		fieldNames: { label: "port_name", value: "code" },
		render: (scope: { row: any }) => {
			return <>{scope.row.port ? scope.row.port.port_name : ""}</>;
		}
	},
	{
		prop: "weight",
		label: "结算重量(kg)",
		width: 120
	},
	{
		prop: "total_amount",
		label: "申报价值",
		width: 120
	},
	{ prop: "batch_no", label: "批次号", width: 150, search: { el: "input" } },
	{
		prop: "created",
		label: "下单时间",
		width: 180,
		search: {
			el: "date-picker",
			span: 1,
			props: {
				type: "datetimerange",
				valueFormat: "YYYY-MM-DD HH:mm:ss",
				defaultTime: [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]
			}
		}
	},
	{
		prop: "print_first_count",
		label: "主运单打印次数",
		width: 120
	},
	{
		prop: "print_second_count",
		label: "从运单打印次数",
		width: 120
	},
	{
		prop: "print_label_count",
		label: "标签打印次数",
		width: 120
	},
	{
		prop: "label_data.is_error",
		label: "异常订单",
		enum: [
			{
				errorLabel: "是",
				errorStatus: true
			},
			{
				errorLabel: "否",
				errorStatus: false
			}
		],
		width: 100,
		search: { el: "select", props: { filterable: true } },
		fieldNames: { label: "errorLabel", value: "errorStatus" },
		isShow: false, //在列表中不显示
		render: (scope: { row: any }) => {
			return (
				<>
					<el-tag type={scope.row.label_data.is_error ? "success" : "danger"}>
						{scope.row.label_data.is_error ? "是" : "否"}
					</el-tag>
				</>
			);
		}
	},
	{
		prop: "label_data.is_collect",
		label: "是否揽收",
		enum: [
			{
				collectLabel: "是",
				collectStatus: true
			},
			{
				collectLabel: "否",
				collectStatus: false
			}
		],
		width: 100,
		search: { el: "select", props: { filterable: true } },
		fieldNames: { label: "collectLabel", value: "collectStatus" },
		isShow: false, //在列表中不显示
		render: (scope: { row: any }) => {
			return (
				<>
					<el-tag type={scope.row.label_data.is_collect ? "success" : "danger"}>
						{scope.row.label_data.is_collect ? "是" : "否"}
					</el-tag>
				</>
			);
		}
	},
	{
		prop: "label_data.is_complete",
		label: "是否完善",
		enum: [
			{
				completeLabel: "是",
				completeStatus: true
			},
			{
				completeLabel: "否",
				completeStatus: false
			}
		],
		width: 100,
		search: { el: "select", props: { filterable: true } },
		fieldNames: { label: "completeLabel", value: "completeStatus" },
		isShow: false, //在列表中不显示
		render: (scope: { row: any }) => {
			return (
				<>
					<el-tag type={scope.row.label_data.is_complete ? "success" : "danger"}>
						{scope.row.label_data.is_complete ? "是" : "否"}
					</el-tag>
				</>
			);
		}
	},
	{
		prop: "label_data.is_pay",
		label: "是否支付",
		enum: [
			{
				payLabel: "是",
				payStatus: true
			},
			{
				payLabel: "否",
				payStatus: false
			}
		],
		width: 100,
		search: { el: "select", props: { filterable: true } },
		fieldNames: { label: "payLabel", value: "payStatus" },
		isShow: false, //在列表中不显示
		render: (scope: { row: any }) => {
			return (
				<>
					<el-tag type={scope.row.label_data.is_pay ? "success" : "danger"}>{scope.row.label_data.is_pay ? "是" : "否"}</el-tag>
				</>
			);
		}
	},
	{
		prop: "is_print",
		label: "面单是否打印",
		enum: [
			{
				collectLabel: "是",
				collectStatus: 1
			},
			{
				collectLabel: "否",
				collectStatus: 0
			}
		],
		width: 100,
		search: { el: "select", props: { filterable: true } },
		fieldNames: { label: "collectLabel", value: "collectStatus" },
		isShow: false //在列表中不显示
	},
	{
		prop: "is_print_label",
		label: "标签是否打印",
		enum: [
			{
				collectLabel: "是",
				collectStatus: 1
			},
			{
				collectLabel: "否",
				collectStatus: 0
			}
		],
		width: 100,
		search: { el: "select", props: { filterable: true } },
		fieldNames: { label: "collectLabel", value: "collectStatus" },
		isShow: false //在列表中不显示
	},
	{ prop: "operation", label: "操作", fixed: "right", width: 300, align: "center" }
];

// 删除用户信息
const deleteAccount = async (params: any) => {
	// await useHandleData(orderCancel, { tid: params.tid }, `收件人:${params.receiver.name}\n废弃订单【${params.tid}】`);
	// proTable.value.getTableList();
	ElMessageBox.alert(
		"<div>收件人: " + params.receiver.name + "</div>" + "<div>系统单号: " + params.tid + "</div>" + "是否废弃，废弃后不可恢复",
		"温馨提示",
		{
			dangerouslyUseHTMLString: true,
			showCancelButton: true,
			confirmButtonText: "废弃",
			cancelButtonText: "取消"
		}
	).then(action => {
		orderCancel({
			tid: params.tid
		}).then((res: any) => {
			ElMessage.success("废弃成功");
			proTable.value.getTableList();
		});
	});
};
//
const getPages = () => {
	let querys: any = _.cloneDeep(param.value);
	querys.page = 1;
	return new Promise<any>((resolve, reject) => {
		orderList(querys).then((res: any) => {
			resolve(Math.ceil(res.data.count / querys.limit));
		});
	});
};
const getExcelList = (page: number) => {
	let querys: any = _.cloneDeep(param.value);
	querys.page = page;
	return new Promise<any>((resolve, reject) => {
		orderList(querys).then((res: any) => {
			resolve(res.data.list);
		});
	});
};
//导出表格
const ExportXlsx = async () => {
	let list: any = [];
	let dataList: any = [];
	let pages = await getPages();
	for (let i = 1; i <= pages; ++i) {
		list = list.concat(await getExcelList(i));
	}
	list.forEach((item: any) => {
		let json_fields: any = {
			系统订单号: " " + item.tid,
			集包号: item.package_no || item.first_waybill_no,
			主运单号: item.first_waybill_no,
			从运单号: item.second_waybill_no,
			状态:
				item.status == 102
					? "待取号"
					: item.status == 103
					? "已取号"
					: item.status == 104
					? "已发货"
					: item.status == 201
					? "已废弃"
					: "",
			用户昵称: _.get(item.user, "username", ""),
			客户昵称: _.get(item.client, "username", ""),
			客户唛头: _.get(item.receiver, "user_mark", ""),
			来源单号: item.order_no,
			收件人: _.get(item.receiver, "name", ""),
			电话: "+" + _.get(item.receiver, "area_code", "") + " " + _.get(item.receiver, "mobile", ""),
			地址:
				_.get(item.receiver, "nation", "") +
				_.get(item.receiver, "province", "") +
				_.get(item.receiver, "city", "") +
				_.get(item.receiver, "district", "") +
				_.get(item.receiver, "detailed", ""),
			邮编: _.get(item.receiver, "postcode", ""),
			走件渠道: _.get(item.channel, "name", ""),
			货物类型: _.get(item.goods_type, "name", ""),
			大小件: item.size == 0 ? "未选择" : item.size == 1 ? "小件" : item.size == 2 ? "大件" : "",
			// 订单类型: item.order_type == 0 ? "未选择" : item.order_type == 1 ? "仓储" : item.order_type == 2 ? "非仓储" : "",
			// 送货方式:
			// 	item.delivery_method == 0
			// 		? "未选择"
			// 		: item.delivery_method == 1
			// 		? "上门取件"
			// 		: item.delivery_method == 2
			// 		? "自送货物"
			// 		: "",
			快递产品类型: item.express_type == 0 ? "未选择" : item.express_type == 1 ? "标快" : item.express_type == 2 ? "特快" : "",
			批次号: item.batch_no,
			"揽件重量(kg)": item.weight_pickup,
			"发运重量(kg)": item.weight_send,
			下单时间: item.created,
			主运单打印次数: item.print_first_count,
			从运单打印次数: item.print_second_count,
			标签打印次数: item.print_label_coun
		};
		goodsCateList.value.forEach((element: any) => {
			json_fields[element] = "";
			item.item.forEach((i: any) => {
				if (i.cate2 && i.cate2.name == element) {
					json_fields[element] = i.num;
				}
			});
		});
		dataList.push(json_fields);
	});

	// 创建工作表
	const data = XLSX.utils.json_to_sheet(dataList);
	// 创建工作簿
	const wb = XLSX.utils.book_new();
	// 将工作表放入工作簿中
	XLSX.utils.book_append_sheet(wb, data, "data");
	// 生成文件并下载
	XLSX.writeFile(wb, "我的订单导出.xlsx");
};
// 打开 drawer(新增、查看、编辑)
const drawerRef = ref();
const openDrawer = (title: string, rowData: any = {}) => {
	rowData.user_mark = rowData.receiver.user_mark;
	rowData.client_address = rowData.receiver;

	let params = {
		title,
		rowData: { ...rowData },
		isView: title === "查看",
		api: title === "新增" ? orderUpdate : title === "编辑" ? orderUpdate : "",
		getTableList: proTable.value.getTableList
	};
	drawerRef.value.acceptParams(params);
};
</script>
<style scoped>
.selectClass {
	position: relative;
	top: -8px;
	left: 10px;
}
</style>
